package com.china08.yxyapi.service.manage.tec.teaching.homework.workstatis1.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.api.manage.tec.teaching.homework.workstatis.WorkStatisticsQues2V1Controller.RespModel;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.workstatis1.WorkStatisticsQues2V1Service;
import com.china08.yxyapi.util.DateUtils;

// 通知类
@Service
public class WorkStatisticsQues2V1ServiceImpl implements WorkStatisticsQues2V1Service {

    @Autowired
    HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Override
    public List<RespModel> statistics(String classId, Integer type, String subject, String stage) {
        // type 类型 1-每天， 2-每周， 3-每月
        if (type == 1) { //
            return this.findStatistics1(classId, subject, stage);
        } else if (type == 2) { //
            return this.findStatistics2(classId, subject, stage);
        } else if (type == 3) { //
            return this.findStatistics3(classId, subject, stage);
        }
        return new ArrayList<RespModel>();
    }

    /**
     * 班级每天作业统计
     * <p>
     * 当前时间后推7天
     */
    private List<RespModel> findStatistics1(String classId, String subject, String stage) {
        // 周一 0-点时间
        Date beginDate = DateUtils.getFirstDay(DateUtils.getMondayOfThisWeek(new Date()));
        // 周日 23:59:59 999-点时间
        Date endDate = DateUtils.getTimesnight(DateUtils.getSundayOfThisWeek(new Date()));
        // ##
        List<HomeworkTaskReport> homeworkTaskReports = null;
        if (subject == null || subject.equals("0") || subject.trim().length() == 0) {
            homeworkTaskReports = homeworkTaskReportRepository
                    .findByClassIdAndPublishDateGreaterThanEqualAndPublishDateLessThanEqual(classId, beginDate, endDate,
                            stage);
        } else {
            homeworkTaskReports = homeworkTaskReportRepository
                    .findByClassIdAndSubjectAndPublishDateGreaterThanEqualAndPublishDateLessThanEqual(classId, subject,
                            beginDate, endDate, stage);
        }
        return this.assembly(homeworkTaskReports, classId);
    }

    /**
     * 班级每周作业统计
     * <p>
     * 当周时间后推7周
     */
    private List<RespModel> findStatistics2(String classId, String subject, String stage) {
        // 月初 0-点时间
        Date beginDate = DateUtils.getFirstDay(DateUtils.getMothOfFirstDay(new Date()));
        // 月末 23:59:59 999-点时间
        Date endDate = DateUtils.getTimesnight(DateUtils.getMothOfLastDay(new Date()));
        // ##
        List<HomeworkTaskReport> homeworkTaskReports = null;
        if (subject == null || subject.equals("0") || subject.trim().length() == 0) {
            homeworkTaskReports = homeworkTaskReportRepository
                    .findByClassIdAndPublishDateGreaterThanEqualAndPublishDateLessThanEqual(classId, beginDate, endDate,
                            stage);
        } else {
            homeworkTaskReports = homeworkTaskReportRepository
                    .findByClassIdAndSubjectAndPublishDateGreaterThanEqualAndPublishDateLessThanEqual(classId, subject,
                            beginDate, endDate, stage);
        }
        return this.assembly(homeworkTaskReports, classId);
    }

    /**
     * 班级每月作业统计
     * <p>
     * 当前月份后推6个月
     */
    private List<RespModel> findStatistics3(String classId, String subject, String stage) {
        // 学期开始 0-点时间
        Date beginDate;
        try {
            beginDate = this.termBeginDate();
        } catch (ParseException e) {
            beginDate = null;
        }
        // 学期结束 23:59:59 999-点时间
        Date endDate;
        try {
            endDate = this.termEndDate();
        } catch (ParseException e) {
            endDate = null;
        }
        // ##
        List<HomeworkTaskReport> homeworkTaskReports = null;
        if (subject == null || subject.equals("0") || subject.trim().length() == 0) {
            homeworkTaskReports = homeworkTaskReportRepository
                    .findByClassIdAndPublishDateGreaterThanEqualAndPublishDateLessThanEqual(classId, beginDate, endDate,
                            stage);
        } else {
            homeworkTaskReports = homeworkTaskReportRepository
                    .findByClassIdAndSubjectAndPublishDateGreaterThanEqualAndPublishDateLessThanEqual(classId, subject,
                            beginDate, endDate, stage);
        }
        return this.assembly(homeworkTaskReports, classId);
    }

    // 数据组装
    private List<RespModel> assembly(List<HomeworkTaskReport> homeworkTaskReports, String classId) {
        // 校验
        if (homeworkTaskReports == null || homeworkTaskReports.size() == 0) { return new ArrayList<>(); }
        // return
        List<RespModel> respModels = new ArrayList<>();
        // ##
        // ##
        Map<String, HomeworkTaskReport> maps = new HashMap<String, HomeworkTaskReport>();
        homeworkTaskReports.forEach(homeworkTaskReport -> {
        	maps.put(homeworkTaskReport.getStudentId(), homeworkTaskReport);
        });
        List<String> stuIds = new ArrayList<String>();
        for (String student : maps.keySet()) {
            stuIds.add(student);
        }
        // 获取时间范围内任务taskIds
        List<String> taskIds = new ArrayList<String>();
        for (HomeworkTaskReport homeworkTaskReport : homeworkTaskReports) {
            // 必须是含有通知类的才做处理
            if (homeworkTaskReport.getTaskType().contains("1")) {
                // 只统计已完成或者已批阅
                if (homeworkTaskReport.getStatusOfFinished() == 1 || homeworkTaskReport.getStatusOfFinished() == 2) {
                    taskIds.add(homeworkTaskReport.getTaskId());
                }
            }
        }
        // 获取学生通知试题得分
        List<HomeworkTaskReportQues> homeworkTaskReportQuesLst = homeworkTaskReportQuesRepository
                .findByClassIdAndStudentIdInAndTaskIdInAndQuestionType(classId, stuIds, taskIds, "2");
        // ##
        maps.keySet().forEach(stuId -> {
        	// ##
        	HomeworkTaskReport taskReport = maps.get(stuId);
            // return
            RespModel respModel = new RespModel();
            // ##
            String studentId = taskReport.getStudentId();
            String studentNick = taskReport.getStudentNick();
            String avatar = taskReport.getAvatar();
            int total = 0; // 总作业数目
            int doneTotal = 0; // 完成人数
            Double score = 0d; // 得分率(总数)
            // ##
            for (HomeworkTaskReport homeworkTaskReport : homeworkTaskReports) {
                // 必须是含有通知类的才做处理
                if (homeworkTaskReport.getTaskType().contains("1")) {
                    if (homeworkTaskReport.getStudentId() != null && homeworkTaskReport.getStudentId().equals(stuId)) {
                        studentId = homeworkTaskReport.getStudentId();
                        studentNick = homeworkTaskReport.getStudentNick();
                        avatar = homeworkTaskReport.getAvatar();
                        total++;
                        if (homeworkTaskReport.getStatusOfFinished() == 1
                                || homeworkTaskReport.getStatusOfFinished() == 2) {
                            doneTotal++;
                            score = score + homeworkTaskReport.getScoreRate();
                        }
                    }
                }
            }
            // ##
            /*for (HomeworkTaskReportQues homeworkTaskReportQues : homeworkTaskReportQuesLst) {
                if (homeworkTaskReportQues.getStudentId() != null
                        && homeworkTaskReportQues.getStudentId().equals(stuId)) {
                    score = score + (homeworkTaskReportQues == null ? 0 : homeworkTaskReportQues.getMark());
                }
            }*/

            // ##
            respModel.studentId = studentId;
            respModel.studentNick = studentNick;
            respModel.avatar = avatar;
            respModel.total = total;
            respModel.doneTotal = doneTotal;
            respModel.scoreRate = this.getDouble(score.doubleValue(), doneTotal);
            respModels.add(respModel);
        });
        return respModels;
    }

    // 学期开始时间
    private Date termBeginDate() throws ParseException {
        // 作业系统-作业统计-按照学期统计: 3月1日——8月30日 9月1日——2月29日
        // 一年最多跨越三个学期
        Date termBeginDate1 = DateUtils.formatStrDate((DateUtils.year(new Date()) - 1) + "-09-01 00:00:00");
        Date termEndDate1 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-02-27 59:59:59");

        Date termBeginDate2 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-02-28 00:00:00");
        Date termEndDate2 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-08-31 59:59:59");

        Date termBeginDate3 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-09-01 00:00:00");
        Date termEndDate3 = DateUtils.formatStrDate((DateUtils.year(new Date()) + 1) + "-02-27 59:59:59");

        // 判断当前时间是在那个学期
        Date date = new Date();
        if ((date.getTime() - termBeginDate1.getTime() >= 0) && (date.getTime() - termEndDate1.getTime() <= 0)) {
            return termBeginDate1;
        } else if ((date.getTime() - termBeginDate2.getTime() >= 0) && (date.getTime() - termEndDate2.getTime() <= 0)) {
            return termBeginDate2;
        } else if ((date.getTime() - termBeginDate3.getTime() >= 0)
                && (date.getTime() - termEndDate3.getTime() <= 0)) { return termBeginDate3; }

        return null;
    }

    // 学期结束时间
    private Date termEndDate() throws ParseException {
        // 作业系统-作业统计-按照学期统计: 3月1日——8月30日 9月1日——2月29日
        // 作业系统-作业统计-按照学期统计: 3月1日——8月30日 9月1日——2月29日
        // 一年最多跨越三个学期
        Date termBeginDate1 = DateUtils.formatStrDate((DateUtils.year(new Date()) - 1) + "-09-01 00:00:00");
        Date termEndDate1 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-02-27 59:59:59");

        Date termBeginDate2 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-02-28 00:00:00");
        Date termEndDate2 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-08-31 59:59:59");

        Date termBeginDate3 = DateUtils.formatStrDate(DateUtils.year(new Date()) + "-09-01 00:00:00");
        Date termEndDate3 = DateUtils.formatStrDate((DateUtils.year(new Date()) + 1) + "-02-27 59:59:59");

        // 判断当前时间是在那个学期
        Date date = new Date();
        if ((date.getTime() - termBeginDate1.getTime() >= 0) && (date.getTime() - termEndDate1.getTime() <= 0)) {
            return termEndDate1;
        } else if ((date.getTime() - termBeginDate2.getTime() >= 0) && (date.getTime() - termEndDate2.getTime() <= 0)) {
            return termEndDate2;
        } else if ((date.getTime() - termBeginDate3.getTime() >= 0)
                && (date.getTime() - termEndDate3.getTime() <= 0)) { return termEndDate3; }

        return null;
    }

    // 格式转化
    private Double getDouble(Double d1, int count) {
        if (count == 0) { return 0d; }
        if (d1 <= 0) { return 0d; }
        Double x1 = d1 / count;
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
        double parse = Double.parseDouble(df.format(x1));
        return parse;
    }
}
